<?php

namespace Wckc\Controller;
use Think\Page;
use Think\Controller;

/**
 * 五彩课程学生管理控制器
 * @author水月居 <singliang@163.com>
 */
class StudentController extends Controller {
	function _initialize()
    {
        header("Content-Type:text/html;charset=utf-8"); 
        if (!is_login()) {
            $this->error('本模块必须登录后才能使用。',U('ucenter/member/login'));
        }

         $this->studentModel=D('Wckc/WckcStudent'); 
         $this->socreModel=D('Wckc/WckcStudentScore');       
         $this->jiemuModel=D('Wckc/WckcJiemu');       
         $this->courseModel=D('Wckc/WckcCourse');
         $this->classModel=D('StudentClass');
         $this->filesModel=D('Wckc/WckcFiles');
         $this->yearModel=D('Year');
         $this->termModel=D('YearTerm');
         $this->curTerm=$this->termModel->where('cur=1')->getfield('term');
         $this->curYear=I('year',$this->yearModel->where('cur=1')->getfield('year'));
         $this->termlist=$this->termModel->field('term, term_ch')->select();

         $catTitle=modC('PAPER_CATEGORY_TITLE','五彩课程','Wckc');
         $sub_menu['left'][]= array('tab' => 'home', 'title' => $catTitle, 'href' =>  U('index'));
         $this->assign('sub_menu', $sub_menu);
         $this->assign('current','home');
         
    }
    /*清除学生数据*/
   public function deleteallstudent(){
    $pass=I('pass','');
    if($pass=='ok'){
        //清除表中的数据，id重新从1开始
        $sql = 'TRUNCATE table `wgy_wckc_student`';
        $result=M()->query($sql);
        // $map=array('status'=>1);
        // $result = $this->studentModel->where($map)->delete();
        $this->success('学生信息清除成功');

    }else{
       $this->error('口令错误，注意本操作将清除本学年中的学生数据'); 
    }

   }

    /**
     * 用户管理首页
    */
    public function index(){
        $class=I('class',cookie('class'));
        $class = $class?$class:"请选择班级" ; //设置学生班级
        if(cookie('aClass')!=$class) cookie('aClass',$class); 
        
		$where = $class?array("class"=>$class,"status"=>"1"):array("status"=>"1");
        $studentModel=$this->studentModel;

        $list=$studentModel->relation(true)->order("id asc")->where($where)->limit(42)->select();

        $map['wckcstatus']=1;
        $order=array(
            'sort'=>'asc'
            );
		  $classlist=$this->classModel->field("bj_name")->where($map)->order($order)->select();
	    $this->assign('_aClass',$class);
		  $this->assign('_class', $classlist);
        $this->assign('_list', $list);

        //dump($list);die;
        $this->meta_title = '学生信息'; 
        $this->display();
    }
    /*
    **查看未报名学生名单*
    */    
    public function index0(){

        $class=I('class',cookie('class'));

        if(cookie('class')!=$class) cookie('class',$class);
        $aClass = $class?$class:"请选择班级" ; //设置学生班级
        if('所有班级'==$class) $class=0;        
        $where = $class ? array("class"=>$class,"status"=>"1",'cid'=>0):array("status"=>"1",'cid'=>0);
        
        $studentModel=$this->studentModel;
       //dump($studentModel);exit;
       
        $list=$studentModel->relation(true)->order("sid asc")->where($where)->limit(60)->select();
        $page=I('page',1, 'intval' );
        
        $r=I('r',20);
        $stlist=$studentModel->relation(true)->getListByPage($where,$page,$order,$field='*',$r);

        $map['wckcstatus']=1;
        $order=array(
            'sort'=>'asc'
            );
        $class=$this->classModel->field("bj_name")->where($map)->order($order)->select();
        $this->assign('_aClass',$aClass);
        $this->assign('_class', $class);
        $this->assign('_list', $stlist['0']);       
        $this->assign('totalPageCount',$stlist['1']);
        $this->assign('r',$stlist['2']);//每页几条记录 
       
        $this->meta_title = '学生信息';
        $this->display();
    }


    /**
     * 修改学生选课信息
     * @author singliang <singliang@163.com>
     */
    
    public function selectCourse($sid=0){
        //选课时间限制
        $limit_time=strtotime(C('WCKC_SELECT_DATE_LIMIT'));//选课限制时间
        $time = time();//当前时间

        if($time>$limit_time){
            $this->error('选课截止日期为： '.C('WCKC_SELECT_DATE_LIMIT').'，超期不能继续调整课程',U('/Wckc/Student/index'),5); 
        }

        //$start_date=strtotime('2009-9-1');
        $student = $this->studentModel->find(I('sid'));
        $this->assign('Student', $student);
        $map['grade'] =array('like',"%".$student['grade']."%");
        $map['year'] =$this->curYear;
        $map['status'] = 1;
        $order=array('shengyu'=>'desc');
        $courselist=$this->courseModel->where($map)->order($order)->limit(50)->select();

        $this->assign('clist', $courselist);
        $this->assign('student', $student);
        $this->meta_title = '学生选课';
        $this->display();
    }
    /**
     * 清除学生选课信息
     * @author singliang <singliang@163.com>
     */
    public function truncate($sid=0){
        $studentModel=$this->studentModel;
            $data = array(
            'id'             => I('sid'),
            'cid'             => 0,
            'update_time' => NOW_TIME,
            'update_ip'   => get_client_ip(1),
        );

         $cur['class']=I('class');
         $res = $studentModel->save($data);

        if(!$res){
            $this->error($studentModel->getError());
        }else{
            $this->success('清除成功！', U('student/index',$cur));
        }

    }
	//保存选课程信息
	 public function saveStudentCourse(){
        $studentModel=$this->studentModel;
        $courseModel=$this->courseModel;
        $sid=I('sid');//学生id
        $cid=I('cid');//课程id

        if(C('WCKC_LIMIT_NUM')){
            $aMap['cid']=$cid;//课程代号   
            $studenCount=$studentModel->where($aMap)->count();
            $limitNum=$courseModel->where($aMap)->getField('number');
            if($limitNum<=$studenCount){
                $this->error('该课程人数已满，选择其他班级可以吗?',U('Wckc/Student/selectCourse',array('sid'=>$sid)),5); 
            }
        }
        $data = array(
            'id'              => $sid,//学生id
            'cid'             => $cid,
            'update_time'     => NOW_TIME,
            'update_ip'       => get_client_ip(1),
        );
        // dump($data);die;

           
           $res =$studentModel->save($data);
           
        if(!$res){
            $this->error($studentModel->getError());
        }else{
			//更新选课人数
			$cdata['cid']=I('cid');
			$cdata['count']=$studentModel->where($cdata)->count();
            $cdata['number']=$courseModel->where(array('cid'=>$cdata['cid']))->getField('number');
            $cdata['shengyu']=$cdata['number']-$cdata['count'];
		  	$courseModel->save($cdata);
			$cur['class']=I('class');
            $cur['sid']=$sid+1;	
            $this->success('选课成功！', U('Student/selectCourse',$cur), 1);
        }
    }
     /**
     * 查询学生课程成绩
     * @author singliang <singliang@163.com>
     */  
  public function classScore($class="请选择班级"){
        $studentModel=$this->studentModel;
        $map['wckcstatus']=1;
        $classModel=$this->classModel;
        $clist=$classModel->field("id, bj_name")->where($map)->order(array('sort'=>"asc"))->select();

        //获取学生信息         
          $cur['class']=$aclass= I('class')?I('class'):$class;//获取班级名称
          $map['class']=$aclass;
         //dump($clist);
       
        $order=array('grade'=>'asc','code'=>'asc');
       
        $stlist=$studentModel->relation(true)
                ->order($order)->where($map)->limit('42')->select();
        //echo $curriculum->getLastSql();

        //获取当前班级信息
        if("请选择班级"==$aclass){
            $cur['bj_name']="请选择班级";
             }else{
                $cur['bj_name']=$aclass;
            }

        $this->assign('_cur', $cur);
        $this->assign('classlist', $clist);
        $this->assign('student', $stlist);
	 $this->display();
     }

     /**
     * 查询优秀学员
     * @author singliang <singliang@163.com>
     */  
    
     public function outstand(){
     	$term=I('term',$this->curTerm);

        $cur['term']=$term;     
        
         $map['outstand'] = 1;
         $term_list=M('YearTerm')->field('term,term_ch')->select();
        $order=array('cid'=>'asc','grade'=>'asc','code'=>'asc');

        if($term==$this->curTerm){       
        $stlist=$this->studentModel->relation(true)
        ->field("update_time,update_ip",true)        
        ->order($order)->where($map)->select();
        

        }else{
          $map['term']=$term;
          $stlist=$this->socreModel
          ->field('id, cname, term, class, code, sex, student as name, score, outstand, update_time as scoreuptime')
          ->where($map)->select(); 
        }
        //dump($stlist);
        $termmap=array('term'=>$term);
        $cur=M('YearTerm')->field('term,term_ch')->where($termmap)->find();
       // dump($cur);die;

        $this->assign('cur',$cur);
        $this->assign('term_list',$term_list);
        $this->assign('student', $stlist);
	    $this->display();
     }


     /**
     * 学期成绩归档
     * @author singliang <singliang@163.com>
     */  
  public function updateScoredata(){
    	$uid=is_login();    	
    	if($uid!=1){
    		 $this->error('请先用管理员账号登录,再使用本功能!'); 		
    	}else{
    		$error='只有管理员才有权限更新学期成绩 , <br>输入的学期代号必须正确';
    	}
    $term=I('term',$this->curTerm);

	if(IS_POST){ 
        $term=I('term');       
        $term2=I('term2');
        // dump($term2);dump($this->curTerm);//die;

		if($term2!=$term) {
            $error='请输入正确的学期代号';
           $this->error($error);			
		}else{

        //获取学生信息
        
        $order=array('grade'=>'asc','class'=> 'asc','code'=>'asc');
        $map["status"] = 1;       
        $stlist=$this->studentModel->relation(true)
        //->field("sid,code,class,name,sex,cname,score,outstand,scoreuptime")
        ->order($order)->where($map)->select();
        //整理插入数据$data
        foreach($stlist as $v){
        	$data[]=array(
        		'grade'    => $v['grade'] ,
        		'term'     => $term, //配置项中的当前学期
        		'class'    => $v['class'],
        		'code'     => $v['code'],
        		'student'  => $v['name'],
        		'sex'      => $v['sex'],
        		'cname'    => $v['cname'],
        		'teacher'  => $v['teacher'],
        		'score'    => $v['score'],
        		'outstand' => $v['outstand'],
        		'update_time'  => $v['scoreuptime'], //将日期转为数字串
        		);
        }
        $count=count($data);
       $socreModel=$this->socreModel;
       $sql_num=$socreModel->addall($data);//更新到相应数据库中

       $msg='期末成绩更新成功，从'.$sql_num.'开始共'.$count.'条学生成绩记录被汇总到数据库';
       $this->success($msg,U('Student/deleteTermScore'));//数据汇总后删除相应的成绩
       }

        
     }

      
      $this->assign('term', $term);
      $this->assign('error_msg', $error);
      $this->display(); 
	 
     }
     public function deleteTermScore(){
     	$studentModel=$this->studentModel;
     	$setvalue=array(
     		'score'=>'',
     		'outstand'=>''
     		);
     	
     	$rs=$studentModel->where('status=1')->setField($setvalue);
     	//dump($studentModel->getLastSql());
 	    if($rs !== false){
 	    	$this->success('数据更新成功！',U('Student/updateScoredata'));
		        echo '数据更新成功！';
		    }else{
		        echo '没更新任何数据！';
		    }
		    die;
	 }


}